package com.swallow.weixin.base.controller;

import com.swallow.weixin.base.service.IBaseService;
import com.swallow.weixin.entity.vo.ResultVO;
import com.swallow.weixin.enums.GlobalEnum;
import com.swallow.weixin.utils.ResponseBuilderUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * @author swallow
 */
public abstract class AbstractBaseController<T extends Serializable,ID extends Serializable> {

    private static final Logger logger = LoggerFactory.getLogger(AbstractBaseController.class);

    protected abstract IBaseService<T> getBaseService();

//    /**
//     * 分页查询
//     */
//    @GetMapping(value = "/list")
//    public ResultVO getList(T entity,@RequestParam(value = "pageNo",required = false,defaultValue = "1") Integer pageNo,
//                            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize,
//                            HttpServletRequest request, HttpServletResponse response){
//        logger.debug("pageNo:{},pageSize:{}", pageNo,pageSize);
//
//        return null;
//    }

    /**
     * 通过id 查询
     */
    @GetMapping(value = "/{id}")
    public ResultVO loadById(@PathVariable(value = "id") ID id, HttpServletRequest request, HttpServletResponse response){
        logger.debug("id:{}",id);
        T t = getBaseService().getById(id);
        logger.info("id:{},entity:{}",id,t);
        return ResponseBuilderUtil.buildSuccessJson(t);
    }

    /**
     * 添加修改
     */
    @PostMapping(value = "/saveOrUpdate")
    public ResultVO saveOrUpdate(T entity, HttpServletRequest request, HttpServletResponse response) {
        logger.debug("entity:{},request:{},response:{}",entity, request, response);
        String id = request.getParameter("id");
        boolean flag = getBaseService().saveOrUpdate(entity);
        if(flag){
            if(StringUtils.isNotBlank(id)){
                // 返回修改成功
                return ResponseBuilderUtil.buildSuccessJson(GlobalEnum.UPDATE_SUCCESS);
            }else{
                // 返回插入成功
                return ResponseBuilderUtil.buildSuccessJson(GlobalEnum.INSERT_SUCCESS);
            }
        }
        return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.OPERATE_ERROR);
    }

    /**
     * 通过id删除
     */
    @DeleteMapping(value = "/{id}")
    public ResultVO deleteById(@PathVariable(value = "id") ID id, HttpServletRequest request, HttpServletResponse response){
        logger.debug("id:{}",id);
        boolean flag = getBaseService().removeById(id);
        logger.info("id:{},flag:{}",id,flag);
        return ResponseBuilderUtil.buildSuccessJson(flag);
    }
}
